<?php

/**
 * LoginController
 * 
 * @author Martin Bianculli
 * @version 0.2
 */
require_once 'Zend/Controller/Action.php';
require_once 'Click/Form/Login.php';

class LoginController extends Zend_Controller_Action {   

    public function init() {
        $ajax_actions = array('auth', 'logout');
        if (in_array($this->getRequest()->getActionName(), $ajax_actions)) {
            if (!$this->getRequest()->isXmlHttpRequest()) throw new Exception('Invalid method'); 
        }        
        $ajaxContext = $this->_helper->getHelper('AjaxContext');
        foreach ($ajax_actions as $ajax_action) $ajaxContext->addActionContext($ajax_action, 'json');
        $ajaxContext->initContext();        
    }
    
    /**
     * The default action
     */
    public function indexAction() {
        $this->_helper->_layout->setLayout('admin');
        $this->view->messages = $this->_helper->flashMessenger->getMessages();        
        $this->view->form = new Click_Form_Login();
    }

    public function logoutAction() {
    	if (Model_User::logout()) $this->view->email = null; 
    }
    
    public function authAction() {                    
        $form = new Click_Form_Login();
        if (
            !$form->isValid($this->getRequest()->getPost()) || 
            !$this->_authenticate($form->getValue('email'), $form->getValue('password'))
        ){            
            $this->_helper->FlashMessenger('¡Datos Incorrectos! Vuelva a intentar.');
            $this->getResponse()->setHeader('X-Redirect', '/login');
        } else {
            $this->view->email = Model_User::getLoggedUser()->email;                                                            
        }                         
    }
    
    public function authenticateAction() {                
        if ($this->getRequest()->isPost()) {
            $form = new Click_Form_Login(); 
            if ($form->isValid($this->getRequest()->getPost())) {            
                $email = $form->getValue('email');
                $password = $form->getValue('password');     
                if ($this->_authenticate($email, $password)) $this->_helper->redirector('view');            
            } else {                
                $this->_helper->FlashMessenger('¡Datos Incorrectos! Vuelva a intentar.');
            }
        }
        $this->_helper->redirector('index');        
    }
    
    public function viewAction() {
        $user = Model_User::getLoggedUser();
        print_r($user); 
    }
    
    private function _authenticate($email, $password) {
        return Model_User::authenticate($email, $password)->isValid();        
    }
    
}
